const Vue = require('vue')
const exp = require('express')
const server = exp()
const renderer = require('vue-server-renderer').createRenderer()
const createApp = require('./dist/bundle.server.js')['default']

// 设置静态资源目录
server.use('/',exp.static(__dirname+'/dist'))
const clientBundleFileUrl = '/bundle.client.js'

server.get('/api/getHomeInfo',(req,res)=>{
  res.send('SSR发送请求了')
})

// const app = new Vue({
//   template:'<div>hello</div>'
// })


// 服务器端渲染的核心就在于
// 通过vue-server-renderer插件的renderToString()方法，将vue实例转换为字符串插入到html文件中
server.get('*',(req,res)=>{

  const context = {url:req.url}

  createApp(context).then(app=>{
    let state = JSON.stringify(context.state);
    renderer.renderToString(app,(err,html)=>{
      if (err) {
        res.status(500).end('Internal Server Error')
        return
      }
      res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});
      res.end(`
        <!DOCTYPE html>
        <html lang="en">
          <head><title>SSR</title></head>
          <script>window.__INITIAL_STATE__=${state}</script>
          <script src="${clientBundleFileUrl}"></script>
          <body>${html}</body>
        </html>
      `)
    })
  },err=>{
    if(err.code===404){
      res.status(404).end('404')
    }
  })
})
server.listen(9999,()=>{
  console.log("服务器已启动！")
})
